package com.sunnada.edu.system.pub.util;

import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public final class SecurityUtil {

	private static PublicKey sDefPublicKey = buildDefPublicKey();
	private static PrivateKey sDefPrivateKey = buildDefPrivateKey();
	
	private static PublicKey buildDefPublicKey()
	{
		try {
			return KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(
					new BigInteger("B5CE747C46781C81488F169C72828B72233E6E3B70525D2CE088665EC1B61F3F5FC7FE96CFB8BFFA699D61D0316ACC8C021A03ABF703C75510990F95008E4A3303ACF424B3E7EFEA001D0499CE00EB293A79B2054D11852E66D81EABF9B714A0013611059810C4CD670B50AC5D2E6B743049A5297AD38690C25BB3BBF95A331D", 16), 
					//new BigInteger("bac04893b4ef3efdce6755c230b425f7698ec8926a2a3159b899645d9546eadb6c3f19f9f052d5807e161c139ff8dab44bda052e2bf5d8f3daa6ad26b30b491197fc66b8a1e08d9f22dbb22a1137837462afc3cb6a84334b23322079ed1aad699f071b2906d54e28ce6834cce61de5cf2cd1cb834ccc385d2459619903594d4b",16),
					new BigInteger("10001", 16)));
		} catch (InvalidKeySpecException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	private static PrivateKey buildDefPrivateKey()
	{
		 try {
			KeySpec keySpec = new RSAPrivateKeySpec(
			            new BigInteger("B5CE747C46781C81488F169C72828B72233E6E3B70525D2CE088665EC1B61F3F5FC7FE96CFB8BFFA699D61D0316ACC8C021A03ABF703C75510990F95008E4A3303ACF424B3E7EFEA001D0499CE00EB293A79B2054D11852E66D81EABF9B714A0013611059810C4CD670B50AC5D2E6B743049A5297AD38690C25BB3BBF95A331D",16), 
						new BigInteger("86B2563538D48671F67B24CA764067E6015CA0B8E2E7F2E66BD842D81376C641E2C9BEC2A7557ECE9D6F1FE7EAA4F0B50E5D8DB8DB82EE2D04E611D8581813B9E4618D58A6DA3A86C3B0B331FA4FC055DD39686BFB09B9CCDF8B6CFFB36A27CDE1694E118075CD9E9144A18D16450A036B9CEB3A01BAB1AFCFD6796E01F84135", 16));
			    KeyFactory factory = KeyFactory.getInstance("RSA");
			    PrivateKey privateKey = factory.generatePrivate(keySpec);
			    return privateKey;
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
		 return null;
	}
	
	public static String RSAEncrypt(String rawData) throws Exception {
		return ConvertionUtil.BytesToHexString(SecurityUtil.RSAEncrypt(ConvertionUtil.StringToUTF8BytesPadding(rawData)), true);
	}
	
	public static String RSADecrypt(String rawData) {
		return RSADecrypt(rawData, Charset.defaultCharset());
	}
	
	public static String RSADecrypt(String rawData, Charset charset) {
		return new String(SecurityUtil.RSADecrypt(ConvertionUtil.HexStringToBytes(rawData)), charset).trim();
	}
	
	public static byte[] RSAEncrypt(byte[] rawData)
	{
		return RSAEncrypt(sDefPublicKey, rawData);
	}
	
	public static byte[] RSAEncrypt(PublicKey publicKey, byte[] rawData)
	{
		try
		{
			Cipher cp = Cipher.getInstance("RSA/ECB/PKCS1Padding");
			cp.init(Cipher.ENCRYPT_MODE, publicKey);
			
			ByteArrayOutputStream buff = new ByteArrayOutputStream();
			int count = rawData.length / 117;  //一次只能加密117个字节11个字节为对齐
			int start = 0;
			for (int i = 0; i < count; i++)
			{
				buff.write(cp.doFinal(rawData,start,117));
				start += 117;
			}
			
			if (start < rawData.length)
			   buff.write(cp.doFinal(rawData, start, rawData.length - start));
			
			return buff.toByteArray();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static byte[] RSADecrypt(byte[] rawData)
	{
		return RSADecrypt(sDefPrivateKey, rawData);
	}
	
	public static byte[] RSADecrypt(PrivateKey key, byte[]ripeData)
	{
		
		try {
			Cipher cp = Cipher.getInstance("RSA/ECB/PKCS1Padding");
			cp.init(Cipher.DECRYPT_MODE, key);
			
			ByteArrayOutputStream buff = new ByteArrayOutputStream();
			
			int count = ripeData.length / 128;  //解密按128个字节来解
			int start = 0;
			for (int i = 0; i < count; i++)
			{
				buff.write(cp.doFinal(ripeData,start,128));
				start += 128;
			}
			
			if (start < ripeData.length)
			   buff.write(cp.doFinal(ripeData, start, ripeData.length - start));
			
			
			return buff.toByteArray();
			
			//return cp.doFinal(rawData);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	
	private static String byteArrayToBase64(byte[] a, boolean alternate) {
		int aLen = a.length;
		int numFullGroups = aLen / 3;
		int numBytesInPartialGroup = aLen - 3 * numFullGroups;
		int resultLen = 4 * ((aLen + 2) / 3);
		StringBuffer result = new StringBuffer(resultLen);
		char[] intToAlpha = (alternate ? intToAltBase64 : intToBase64);

		// Translate all full groups from byte array elements to Base64
		int inCursor = 0;
		for (int i = 0; i < numFullGroups; i++) {
			int byte0 = a[inCursor++] & 0xff;
			int byte1 = a[inCursor++] & 0xff;
			int byte2 = a[inCursor++] & 0xff;
			result.append(intToAlpha[byte0 >> 2]);
			result.append(intToAlpha[(byte0 << 4) & 0x3f | (byte1 >> 4)]);
			result.append(intToAlpha[(byte1 << 2) & 0x3f | (byte2 >> 6)]);
			result.append(intToAlpha[byte2 & 0x3f]);
		}

		// Translate partial group if present
		if (numBytesInPartialGroup != 0) {
			int byte0 = a[inCursor++] & 0xff;
			result.append(intToAlpha[byte0 >> 2]);
			if (numBytesInPartialGroup == 1) {
				result.append(intToAlpha[(byte0 << 4) & 0x3f]);
				result.append("==");
			} else {
				// assert numBytesInPartialGroup == 2;
				int byte1 = a[inCursor++] & 0xff;
				result.append(intToAlpha[(byte0 << 4) & 0x3f | (byte1 >> 4)]);
				result.append(intToAlpha[(byte1 << 2) & 0x3f]);
				result.append('=');
			}
		}
		// assert inCursor == a.length;
		// assert result.length() == resultLen;
		return result.toString();
	}

	/**
	 * This array is a lookup table that translates 6-bit positive integer index
	 * values into their "Base64 Alphabet" equivalents as specified in Table 1
	 * of RFC 2045.
	 */
	private static final char intToBase64[] = { 'A', 'B', 'C', 'D', 'E', 'F',
			'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
			'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
			'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
			't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',
			'6', '7', '8', '9', '+', '/' };

	/**
	 * This array is a lookup table that translates 6-bit positive integer index
	 * values into their "Alternate Base64 Alphabet" equivalents. This is NOT
	 * the real Base64 Alphabet as per in Table 1 of RFC 2045. This alternate
	 * alphabet does not use the capital letters. It is designed for use in
	 * environments where "case folding" occurs.
	 */
	private static final char intToAltBase64[] = { '!', '"', '#', '$', '%',
			'&', '\'', '(', ')', ',', '-', '.', ':', ';', '<', '>', '@', '[',
			']', '^', '`', '_', '{', '|', '}', '~', 'a', 'b', 'c', 'd', 'e',
			'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
			's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4',
			'5', '6', '7', '8', '9', '+', '?' };

	
	private static byte[] base64ToByteArray(String s, boolean alternate) {
		byte[] alphaToInt = (alternate ? altBase64ToInt : base64ToInt);
		int sLen = s.length();
		int numGroups = sLen / 4;
		if (4 * numGroups != sLen)
			throw new IllegalArgumentException(
					"String length must be a multiple of four.");
		int missingBytesInLastGroup = 0;
		int numFullGroups = numGroups;
		if (sLen != 0) {
			if (s.charAt(sLen - 1) == '=') {
				missingBytesInLastGroup++;
				numFullGroups--;
			}
			if (s.charAt(sLen - 2) == '=')
				missingBytesInLastGroup++;
		}
		byte[] result = new byte[3 * numGroups - missingBytesInLastGroup];

		// Translate all full groups from base64 to byte array elements
		int inCursor = 0, outCursor = 0;
		for (int i = 0; i < numFullGroups; i++) {
			int ch0 = base64toInt(s.charAt(inCursor++), alphaToInt);
			int ch1 = base64toInt(s.charAt(inCursor++), alphaToInt);
			int ch2 = base64toInt(s.charAt(inCursor++), alphaToInt);
			int ch3 = base64toInt(s.charAt(inCursor++), alphaToInt);
			result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
			result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
			result[outCursor++] = (byte) ((ch2 << 6) | ch3);
		}

		// Translate partial group, if present
		if (missingBytesInLastGroup != 0) {
			int ch0 = base64toInt(s.charAt(inCursor++), alphaToInt);
			int ch1 = base64toInt(s.charAt(inCursor++), alphaToInt);
			result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));

			if (missingBytesInLastGroup == 1) {
				int ch2 = base64toInt(s.charAt(inCursor++), alphaToInt);
				result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
			}
		}
		// assert inCursor == s.length()-missingBytesInLastGroup;
		// assert outCursor == result.length;
		return result;
	}

	/**
	 * Translates the specified character, which is assumed to be in the
	 * "Base 64 Alphabet" into its equivalent 6-bit positive integer.
	 * 
	 * @throw IllegalArgumentException or ArrayOutOfBoundsException if c is not
	 *        in the Base64 Alphabet.
	 */
	private static int base64toInt(char c, byte[] alphaToInt) {
		int result = alphaToInt[c];
		if (result < 0)
			throw new IllegalArgumentException("Illegal character " + c);
		return result;
	}

	/**
	 * This array is a lookup table that translates unicode characters drawn
	 * from the "Base64 Alphabet" (as specified in Table 1 of RFC 2045) into
	 * their 6-bit positive integer equivalents. Characters that are not in the
	 * Base64 alphabet but fall within the bounds of the array are translated to
	 * -1.
	 */
	private static final byte base64ToInt[] = { -1, -1, -1, -1, -1, -1, -1, -1,
			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			-1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1,
			-1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
			13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1,
			-1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
			41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 };

	/**
	 * This array is the analogue of base64ToInt, but for the nonstandard
	 * variant that avoids the use of uppercase alphabetic characters.
	 */
	private static final byte altBase64ToInt[] = { -1, -1, -1, -1, -1, -1, -1,
			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			-1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -1,
			62, 9, 10, 11, -1, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 12, 13,
			14, -1, 15, 63, 16, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 17, -1, 18,
			19, 21, 20, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
			40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 22, 23, 24, 25 };

	
	
	public static String Base64Encrypt(byte[] rawData)
	{
		return byteArrayToBase64(rawData, false);
		
	}
	
	public static byte[] Base64Decrypt(String destString)
	{
		return base64ToByteArray(destString, false);
	}
	
	
	// MD5加密
	public static String MD5Encrypt(byte[] rawData) {
		
		try
		{
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(rawData);
			byte[] digestBytes = md5.digest();
    
			String md5Digest =  ConvertionUtil.BytesToHexString(digestBytes, true); //encodeHexString(digestBytes);
			return md5Digest;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		return null;
    }
	
	public static String genDESKeyStr()
	{
		return ConvertionUtil.BytesToHexString(SecurityUtil.genDESKey(), true);
	}
	
	public static byte[] genDESKey()
	{
		try {
			return KeyGenerator.getInstance("DES").generateKey().getEncoded();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static String DESEncrypt(String key, String rawData) throws Exception {
		return ConvertionUtil.BytesToHexString(SecurityUtil.DESEncrypt(
				ConvertionUtil.HexStringToBytes(key), 
				ConvertionUtil.StringToUTF8BytesPadding(rawData)), true);
	}
	
	public static byte[] DESEncrypt(byte[] key, byte[] rawData)
			throws Exception {

		SecretKey desKey = new SecretKeySpec(key, "DES");
		Cipher cp = Cipher.getInstance("DES/ECB/NoPadding");
		cp.init(Cipher.ENCRYPT_MODE, desKey);
		return cp.doFinal(rawData);
	}

	public static String DESDecrypt(String key, String rawData) {
		return DESDecrypt(key, rawData, Charset.defaultCharset());
	}
	
	public static String DESDecrypt(String key, String rawData, Charset charset) {
		return new String(SecurityUtil.DESDecrypt(ConvertionUtil.HexStringToBytes(key), 
				ConvertionUtil.HexStringToBytes(rawData)), charset).trim();
	}
	
	public static byte[] DESDecrypt(byte[] key, byte[] ripeData) {
		try
		{
		SecretKey desKey = new SecretKeySpec(key, "DES");
		Cipher cp = Cipher.getInstance("DES/ECB/NoPadding");
		cp.init(Cipher.DECRYPT_MODE, desKey);
		return cp.doFinal(ripeData);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		return null;
	}
	
	/**
	 * RSA解密
	 */
	public static String RSADecode(String str) {
		try {
			StringBuilder sb = new StringBuilder(new String(RSAUtil.decrypt(
					RSAUtil.getKeyPair().getPrivate(), RSAUtil.hexStringToBytes(str))));
			return URLDecoder.decode(sb.reverse().toString(), "UTF-8");
		} catch (Exception e) {
			return null;
		}
	}
	
}
